package com.cw.jeeyt.controller.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cw.jeeyt.api.dto.response.JsonResultDto;
import com.cw.jeeyt.common.DataTable;
import com.cw.jeeyt.common.ResultData;
import com.cw.jeeyt.common.enums.EnumOperateFlag;
import com.cw.jeeyt.common.web.BaseController;
import com.cw.jeeyt.service.bo.api.ApiDatabaseScriptConfigBo;
import com.cw.jeeyt.service.intf.api.ApiDatabaseScriptConfigService;
import com.cw.jeeyt.service.directive.PageDictDirective;
import com.cw.jeeyt.service.directive.PermissionDirective;
import com.cw.lang.common.utils.CollectionUtil;
import com.cw.lang.mybatis.dto.PageInfo;

/**
 * 数据库脚本导出配置表控制层
 *
* @author chenw
* @version 1.0.0
 */
@Controller
@RequestMapping("/apiDatabaseScriptConfig")
public class ApiDatabaseScriptConfigController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(ApiDatabaseScriptConfigController.class);
    @Resource
    private ApiDatabaseScriptConfigService apiDatabaseScriptConfigService;

    /**
     * 跳转到数据库脚本导出配置表列表查询页面
     *
     * @param apiDatabaseScriptConfigBo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/query")
    public ModelAndView query()
    throws Exception {

        ModelAndView mv = new ModelAndView("api/apiDatabaseScriptConfig_index");
        mv.addObject("permission", new PermissionDirective());
        mv.addObject("PageDict", new PageDictDirective());
        return mv;
    }

    /**
     * 加载DataTable列表数据
     *
     * @param dataTable 请求数据
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/listApiDatabaseScriptConfig")
    public ResultData listApiDatabaseScriptConfig(@RequestBody DataTable dataTable) throws Exception {

        ApiDatabaseScriptConfigBo apiDatabaseScriptConfigBo = JSONObject.parseObject(
            JSON.toJSONString(dataTable.getQueryCond()), ApiDatabaseScriptConfigBo.class);
        if (apiDatabaseScriptConfigBo == null) {
            apiDatabaseScriptConfigBo = new ApiDatabaseScriptConfigBo();
        }
        PageInfo<ApiDatabaseScriptConfigBo> pageInfo = apiDatabaseScriptConfigService.queryByPage(
            apiDatabaseScriptConfigBo, dataTable.getStart(), dataTable.getLength(), dataTable.getOrder()[0]);
        return ResultData.builder()
            .draw(dataTable.getDraw())
            .data(CollectionUtil.isNotEmpty(pageInfo.getList())?pageInfo.getList():new ArrayList())
            .recordsTotal(pageInfo.getTotal())
            .recordsFiltered(pageInfo.getTotal())
            .build();
    }

    /**
     * 跳转到数据库脚本导出配置表表单页面
     *
     * @param operation 操作  add 新增 edit修改 view查看
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-form")
    public ModelAndView editForm(Long id, String operation) throws Exception {

        ModelAndView mv = new ModelAndView("api/apiDatabaseScriptConfig_form");
        ApiDatabaseScriptConfigBo apiDatabaseScriptConfigBo = null;
        if (EnumOperateFlag.ADD.getCode()
            .equals(operation)) {
            apiDatabaseScriptConfigBo = new ApiDatabaseScriptConfigBo();
        } else {
            apiDatabaseScriptConfigBo = apiDatabaseScriptConfigService.getApiDatabaseScriptConfigById(id);
        }
        mv.addObject("apiDatabaseScriptConfig", apiDatabaseScriptConfigBo);
        mv.addObject("operation", operation);
        mv.addObject("PageDict", new PageDictDirective());
        mv.addObject("permission", new PermissionDirective());
        return mv;
    }

    /**
     * 跳转到数据库脚本导出配置表表单页面
     *
     * @param databaseId 数据库id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/toExportScript")
    public ModelAndView editForm(Long databaseId) throws Exception {

        ModelAndView mv = new ModelAndView("api/apiDatabaseScriptConfig_export");
        ApiDatabaseScriptConfigBo apiDatabaseScriptConfigBo = apiDatabaseScriptConfigService.getByDatabaseId(
            databaseId);
        if (apiDatabaseScriptConfigBo == null) {
            apiDatabaseScriptConfigBo = new ApiDatabaseScriptConfigBo();
            apiDatabaseScriptConfigBo.setDatabaseId(databaseId);
        }
        mv.addObject("apiDatabaseScriptConfig", apiDatabaseScriptConfigBo);
        mv.addObject("PageDict", new PageDictDirective());
        mv.addObject("permission", new PermissionDirective());
        return mv;
    }

    /**
     * 跳转到数据库脚本导出配置表表单页面
     *
     * @param databaseId 数据库id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/toExportOracleScript")
    public ModelAndView toExportOracleScript(Long databaseId) throws Exception {

        ModelAndView mv = new ModelAndView("api/apiDatabaseScriptConfig_exportOracle");
        ApiDatabaseScriptConfigBo apiDatabaseScriptConfigBo = apiDatabaseScriptConfigService.getByDatabaseId(
            databaseId);
        if (apiDatabaseScriptConfigBo == null) {
            apiDatabaseScriptConfigBo = new ApiDatabaseScriptConfigBo();
            apiDatabaseScriptConfigBo.setDatabaseId(databaseId);
        }
        mv.addObject("apiDatabaseScriptConfig", apiDatabaseScriptConfigBo);
        mv.addObject("PageDict", new PageDictDirective());
        mv.addObject("permission", new PermissionDirective());
        return mv;
    }

    /**
     * 根据操作类型保存数据库脚本导出配置表数据
     *
     * @param apiDatabaseScriptConfigBo
     */
    @ResponseBody
    @RequestMapping(value = "/saveApiDatabaseScriptConfig", method = RequestMethod.POST)
    public JsonResultDto saveApiDatabaseScriptConfig(ApiDatabaseScriptConfigBo apiDatabaseScriptConfigBo) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            ApiDatabaseScriptConfigBo checkBo = apiDatabaseScriptConfigService.getByDatabaseId(
                apiDatabaseScriptConfigBo.getDatabaseId());
            if (checkBo == null) {
                apiDatabaseScriptConfigService.insert(apiDatabaseScriptConfigBo);
            } else {
                apiDatabaseScriptConfigService.update(apiDatabaseScriptConfigBo);
            }
            jsonResultDto.setMsg("保存成功");
            jsonResultDto.setSuccess(true);
            Map<String, Object> map = new HashMap<>();
            map.put("databaseId", apiDatabaseScriptConfigBo.getDatabaseId());
            jsonResultDto.setResultData(map);
        } catch (Exception e) {
            jsonResultDto.setMsg("保存失败:" + e.getMessage());

            e.printStackTrace();
            logger.error("保存数据库脚本导出配置表失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 删除数据库脚本导出配置表
     *
     * @param apiDatabaseScriptConfigBo
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public JsonResultDto delete(ApiDatabaseScriptConfigBo apiDatabaseScriptConfigBo) throws Exception {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            apiDatabaseScriptConfigService.delete(apiDatabaseScriptConfigBo);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();

            jsonResultDto.setMsg("删除失败：" + e.getMessage());
            logger.error("删除数据库脚本导出配置表失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 导出数据库脚本
     *
     * @param databaseId
     */
    @RequestMapping(value = "/exportScript")
    @ResponseBody
    public void exportScript(HttpServletRequest request, HttpServletResponse response, Long databaseId) {

        try {
            apiDatabaseScriptConfigService.exportScript(databaseId, request, response);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("导出数据库脚本失败：" + e.getMessage());
        }
    }

    /**
     * 导出oracle数据库脚本
     *
     * @param databaseId
     */
    @RequestMapping(value = "/exportOracleScript")
    @ResponseBody
    public void exportOracleScript(HttpServletRequest request, HttpServletResponse response, Long databaseId) {

        try {
            apiDatabaseScriptConfigService.exportOracleScript(databaseId, request, response);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("导出Oracle数据库脚本失败：" + e.getMessage());
        }
    }
}
